package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

import (
	"github.com/lxn/walk"
)

// PathError records an error and the operation and file path that caused it.
type PathError struct {
	Op   string
	Path string
	Err  error
}

func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }

type string_map map[string]string

var onDutyUrl, offDutyUrl string

func main() {
	mapconf := readConf()
	username := mapconf["username"]
	password := mapconf["password"]
	loginUrl := mapconf["loginUrl"]
	onDutyUrl = mapconf["onDutyUrl"]
	offDutyUrl = mapconf["offDutyUrl"]
	fmt.Println(username)
	fmt.Println(password)
	fmt.Println(loginUrl)
	fmt.Println(onDutyUrl)
	fmt.Println(offDutyUrl)
	// We need either a walk.MainWindow or a walk.Dialog for their message loop.
	// We will not make it visible in this example, though.
	mw, err := walk.NewMainWindow()
	if err != nil {
		log.Fatal(err)
	}

	// We load our icon from a file.
	icon, err := walk.NewIconFromFile("img/x.ico")
	if err != nil {
		log.Fatal(err)
	}

	// Create the notify icon and make sure we clean it up on exit.
	ni, err := walk.NewNotifyIcon()
	if err != nil {
		log.Fatal(err)
	}
	defer ni.Dispose()

	// Set the icon and a tool tip text.
	if err := ni.SetIcon(icon); err != nil {
		log.Fatal(err)
	}
	if err := ni.SetToolTip("右键菜单退出。"); err != nil {
		log.Fatal(err)
	}
	// When the left mouse button is pressed, bring up our balloon.
	ni.MouseDown().Attach(func(x, y int, button walk.MouseButton) {
		if button != walk.LeftButton {
			return
		}
		cookies, err := Login(username, password, loginUrl)
		if err != nil {
			if err := ni.ShowCustom(
				"签到工具",
				"签到失败"); err != nil {

				//log.Fatal(err)
			}
		} else {
			err2 := qiandao(cookies, "onDuty", onDutyUrl)
			err1 := qiandao(cookies, "offDuty", offDutyUrl)
			if err2 != nil || err1 != nil {
				if err3 := ni.ShowCustom(
					"签到工具",
					"签到失败"); err3 != nil {

					//log.Fatal(err)
				}
			} else {
				if err := ni.ShowCustom(
					"签到工具",
					"签到成功"); err != nil {

					log.Fatal(err)
				}
			}
		}

	})
	// We put an exit action into the context menu.
	exitAction := walk.NewAction()
	if err := exitAction.SetText("退出"); err != nil {
		log.Fatal(err)
	}
	exitAction.Triggered().Attach(func() {
		walk.App().Exit(0)
	})
	if err := ni.ContextMenu().Actions().Add(exitAction); err != nil {
		log.Fatal(err)
	}

	// The notify icon is hidden initially, so we have to make it visible.
	if err := ni.SetVisible(true); err != nil {
		log.Fatal(err)
	}

	cookies, err := Login(username, password, loginUrl)
	if err != nil {
		if err := ni.ShowInfo("签到小工具", "签到失败."); err != nil {
			log.Fatal(err)
		}
	} else {
		err := qiandao(cookies, "onDuty", onDutyUrl)
		err1 := qiandao(cookies, "offDuty", offDutyUrl)
		if err != nil || err1 != nil {
			if err := ni.ShowInfo("签到小工具", "签到失败."); err != nil {
				//log.Fatal(err)
			}
		} else {
			if err := ni.ShowInfo("签到小工具", "签到成功."); err != nil {
				//log.Fatal(err)
			}
		}
	}
	// Now that the icon is visible, we can bring up an info balloon.
	// Run the message loop.
	go goToQiandao(cookies, ni)
	mw.Run()
}
func readConf() (mapconf string_map) {
	mapconf = make(string_map)
	confurl := "USER.CONF"
	file, err := os.OpenFile(confurl, os.O_RDONLY, 0)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	for {
		//每次读取一行
		line, err := reader.ReadString('\n')
		if err != io.EOF {
			str := string(line)
			conf := strings.Split(str, "=")
			mapconf[strings.TrimSpace(conf[0])] = strings.TrimSpace(conf[1])
		} else {
			break
		}
	}
	return
}
func subString(str string, begin, length int) (substr string) {
	// 将字符串的转换成[]rune
	rs := []rune(str)
	lth := len(rs)

	// 简单的越界判断
	if begin < 0 {
		begin = 0
	}
	if begin >= lth {
		begin = lth
	}
	end := begin + length
	if end > lth {
		end = lth
	}

	// 返回子串
	return string(rs[begin:end])
}
func Login(name, pwd, loginUrl string) (cookies []*http.Cookie, err error) {
	data := make(url.Values)
	data.Set("UserCode", name)
	data.Set("PassWord", pwd)
	resp, err := http.DefaultClient.PostForm(loginUrl, data)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode == 200 {
		robots, err := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
		}
		fmt.Println("报文" + string(robots))
		if strings.Contains(string(robots), " ORA-00001") {

		}
	}
	for _, cookie := range resp.Cookies() {
		cookies = append(cookies, cookie)
	}
	return
}
func qiandao(cookies []*http.Cookie, rp, url string) (err error) {
	req, err1 := http.NewRequest("GET", url+"?actionType="+rp, nil)
	if err1 != nil {
		return err1
	}
	for _, cookie := range cookies {
		req.AddCookie(cookie)
	}
	resp, err2 := http.DefaultClient.Do(req)
	if err2 != nil {
		return err2
	}
	if resp.StatusCode == 200 {
		robots, err := ioutil.ReadAll(resp.Body)
		fmt.Println(string(robots))
		resp.Body.Close()
		if err != nil {
			return err
		}
	}
	return
}
func goToQiandao(cookies []*http.Cookie, ni *walk.NotifyIcon) {
	fmt.Println("进入定时签到")
	timeflag := time.NewTicker(1 * time.Minute)
	for {
		select {
		case <-timeflag.C:
			toQiandao(cookies, ni)
		}
	}
}
func toQiandao(cookies []*http.Cookie, ni *walk.NotifyIcon) {
	func() {
		tipTime := time.Now().Format("2006/01/02/15:04:05")
		min, _ := strconv.Atoi(subString(tipTime, 14, 2))
		fmt.Println(min)
		if (min % 10) == 0 {
			err := qiandao(cookies, "onDuty", onDutyUrl)
			err1 := qiandao(cookies, "offDuty", offDutyUrl)
			if err != nil || err1 != nil {
				if err := ni.ShowInfo("签到小工具", "签到失败."); err != nil {
					//log.Fatal(err)
				}
			} else {
				if err := ni.ShowInfo("签到小工具", "签到成功."); err != nil {
					//log.Fatal(err)
				}
			}
			fmt.Println(tipTime)
		}
	}()

}